package com.shijiangdiya.common;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;

import java.util.*;

public class Generator {
    /**
     * 生成的代码的顶层包名
     */
    private static final String SERVICE_NAME = "code";
    /**
     * 最终包路径
     */
    private static final StringBuilder FINAL_PATH = new StringBuilder();

    /**
     * 表名前缀
     */
    private static String tablePrefix = "t_";


    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help);
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    /**
     * 代码生成器
     */
    public static void main(String[] args) {
        // 目标数据表名
        String[] tableName = scanner("表名，多个英文逗号分割").split(",");
        generateByTables(tableName);
    }

    private static void generateByTables(String... tableNames) {
        AutoGenerator mpg = new AutoGenerator();
        mpg.setTemplateEngine(new VelocityTemplateEngine());
        // 全局配置
        GlobalConfig gc = globalGenerate();
        // 包配置
        PackageConfig pc = packageGenerate();
        // 数据库配置
        DataSourceConfig dsc = dataSourceGenerate();
        // 自定义模板
        TemplateConfig tc = templateGenerate();
        // 策略配置
        StrategyConfig strategy = strategyGenerate(tableNames);
        mpg.setGlobalConfig(gc);
        mpg.setDataSource(dsc);
        mpg.setPackageInfo(pc);
        mpg.setTemplate(tc);
        mpg.setStrategy(strategy);
        mpg.execute();
    }

    /**
     * 数据库配置
     *
     * @return 数据源
     */
    private static DataSourceConfig dataSourceGenerate() {
        YamlPropertiesFactoryBean yamlMapFactoryBean = new YamlPropertiesFactoryBean();
        yamlMapFactoryBean.setResources(new ClassPathResource("application.yml"));
        //获取yml里的参数
        Properties properties = yamlMapFactoryBean.getObject();
        String url = properties.getProperty("spring.datasource.url");
        String driver = properties.getProperty("spring.datasource.driver-class-name");
        String username = properties.getProperty("spring.datasource.username");
        String password = properties.getProperty("spring.datasource.password");
        // 数据库配置
        DataSourceConfig dsc = new DataSourceConfig();
        //数据类型
        dsc.setDbType(DbType.MYSQL);
        dsc.setUrl(url);
        dsc.setDriverName(driver);
        dsc.setUsername(username);
        dsc.setPassword(password);
        return dsc;
    }

    /**
     * 全局配置
     *
     * @return 全局配置
     */
    private static GlobalConfig globalGenerate() {
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        //是否覆盖文件
        gc.setFileOverride(true);
        // 获取顶层目录
        String projectPath = System.getProperty("user.dir");
        // 获取子项目目录
        String path = Generator.class.getClassLoader().getResource("").getPath();
        String levelPath = path.substring(0, path.indexOf("target") - 1);
        if (!projectPath.equals(levelPath)) {
            FINAL_PATH.append(levelPath);
        } else {
            FINAL_PATH.append(projectPath);
        }
        //输出路径
        gc.setOutputDir(FINAL_PATH + "/src/main/java");
        //作者名称
        gc.setAuthor("shijiangdiya");
        //生成后是否自动打开文件
        gc.setOpen(true);
        // XML 二级缓存
        gc.setEnableCache(false);
        //是否使用swagger2
        gc.setSwagger2(true);
        // 自定义文件命名，注意 %s 会自动填充表实体属性！
        gc.setControllerName("%sController");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        //mapper.xml中生成基础resultMap
        gc.setBaseResultMap(true);
        //mapper.xml中生成基础columnList
        gc.setBaseColumnList(true);
        // 主键类型
        gc.setIdType(IdType.ID_WORKER);
        return gc;
    }

    /**
     * 策略配置
     * 主要的表字段映射
     *
     * @param tableName 表名
     * @return 策略配置
     */
    private static StrategyConfig strategyGenerate(String[] tableName) {
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        //表名映射到实体策略，带下划线的转成 驼峰
        strategy.setNaming(NamingStrategy.underline_to_camel);
        //列名映射到类型属性策略，带下划线的转成驼峰
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        // 表名和字段名是否大小写
        strategy.setCapitalMode(false);
        //实体类使用lombok
        strategy.setEntityLombokModel(true);
        //controller使用rest接口模式
        strategy.setRestControllerStyle(true);
        // 继承顶层controller 这里是
        strategy.setSuperControllerClass("com.shijiangdiya.config.AbstractController");
        //设置表名
        strategy.setInclude(tableName);
        //去掉前缀
        strategy.setTablePrefix(tablePrefix);
        strategy.setEntityBooleanColumnRemoveIsPrefix(true);
        // 驼峰转连字符
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setEntityBuilderModel(true);
        return strategy;
    }

    /**
     * 自定义模板
     *
     * @return 模板
     */
    private static TemplateConfig templateGenerate() {
        // 设置模板
        TemplateConfig tc = new TemplateConfig();
        tc.setController("templates/MyController.java.vm")
                .setEntity("templates/MyEntity.java.vm")
                .setService("templates/MyService.java.vm")
                .setServiceImpl("templates/MyServiceImpl.java.vm")
                .setMapper("templates/MyMapper.java.vm")
                .setXml("/templates/MyMapper.xml.vm");
                // 不要源码包内的mapper
        return tc;
    }

    /**
     * 包配置
     *
     * @return 包配置
     */
    private static PackageConfig packageGenerate() {
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(SERVICE_NAME);
        pc.setParent("com.shijiangdiya");
        pc.setEntity("entity");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setMapper("mapper");
        pc.setXml("mapper.xml");
        return pc;
    }
}
